﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;using DICOMViewer.Config;
using Leadtools.Demos;
using Leadtools.Dicom;
using Leadtools.DicomDemos;
using Leadtools.DicomDemos.Scu.CFind;
using Main3DDemo;
using System.Linq;
using System.Runtime.InteropServices;
using DICOMViewer.UC;
using DICOMViewer.Model;
using DICOMViewer.Utility;

namespace DICOMViewer
{
    public partial class MainForm : Form
    {
        public delegate void AddSeriesItemDelegate(DicomDataSet ds);

        private CFind cfind;
        private string patientId;

        private Queue<string> queue = new Queue<string>();
        private string seriesInstance;
        private string studyInstance;
        private string workPath;
        private Thread th;
        private int width;
        private int height;

        private BindPanel bindPanel;
        private MainPanel mainPanel;
        private ProgressForm progessForm;

        #region 处理界面顶部拖动

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();

        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        const int WM_GETTEXT = 0x000B;
        const int WM_SETREDRAW = 11;
        const int FALSE = 0x0000;
        const int TRUE = 0x0001;
        const int WM_CLOSE = 0X0010;

        private void panel_title_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, 0x0112, 0xF012, 0);
        }

        private void tableLayoutPanel_title_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, 0x0112, 0xF012, 0);
        }

        private void cb_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, 0x0112, 0xF012, 0);
        }

        #endregion

        public MainForm()
        {
            InitializeComponent();
            this.MaximizedBounds = Screen.PrimaryScreen.WorkingArea;
            this.SizeChanged += MainForm_SizeChanged;
            FormClosing += MainForm_FormClosing;
            cfind = new CFind
            {
                ImplementationClass = ConstDefineValues.CONFIGURATION_IMPLEMENTATIONCLASS,
                ProtocolVersion = ConstDefineValues.CONFIGURATION_PROTOCOLVERSION,
                ImplementationVersionName = ConstDefineValues.CONFIGURATION_IMPLEMENTATIONVERSIONNAME
            };
            cfind.Status += cfind_Status;
            cfind.FindComplete += cfind_FindComplete;
            cfind.MoveComplete += cfind_MoveComplete;
        }

        private ArgsModel args;

        public MainForm(ArgsModel args) : this()
        {
            this.args = args;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            width = Width;
            height = Height;
            this.WindowState = FormWindowState.Maximized;
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            int changedWidth = this.Width - width;
            int changedHight = this.Height - height;
            //this.panel1.Height = this.panel1.Height + changedHight;
            //this.mainPanel.Width = this.mainPanel.Width + changedWidth;
            width = Width;
            height = Height;
        }

        public volatile bool IsShown = false;

        /// <summary>
        /// Shown事件,内部包含了大量控件、委托挂载逻辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Shown(object sender, EventArgs e)
        {
            //看图控件相关
            mainPanel = new Main3DDemo.MainPanel(this);
            mainPanel.seriesBrowserDialog.DicomDirAdded += mainPanel_DicomDirAdded;
            mainPanel.Dock = DockStyle.Fill;
            mainPanel.Margin = new Padding(0);
            panel_Main.Controls.Add(mainPanel);
            //绑定单子控件相关
            bindPanel = new BindPanel();
            bindPanel.cfind = this.cfind;
            bindPanel.Dock = DockStyle.Fill;
            bindPanel.Margin = new Padding(0);
            bindPanel.ServerGridDoubleClicked += BindPanel_ServerGridDoubleClicked;
            bindPanel.LocalGridDoubleClicked += BindPanel_LocalGridDoubleClicked;
            xtraTabPage_order.Controls.Add(bindPanel);
            //登录欢迎信息相关
            lblWelcome.Text = string.Format("你好，{0}！", Model.LoginInfo.Current?.Name ?? string.Empty);
            //进度窗相关
            progessForm = new ProgressForm(this);
            //给imagesLoader追加事件，实现进度条动画
            mainPanel.seriesBrowserDialog.imagesLoader.ProgressChanged += new System.ComponentModel.
                ProgressChangedEventHandler(
                (s, arg) =>
                {
                    int percentage = arg.ProgressPercentage;
                    // Sending -1 means that a new image (or set of images) has been loaded successfully and added to the Images collection for the user to use.
                    if (arg.ProgressPercentage > -1)
                    {
                        if (arg.UserState is ProgressEventArgs)
                        {
                            // otherwise, the method reports a progress with loading the images, providing a variety of information.
                            ProgressEventArgs progressInformation = (ProgressEventArgs) arg.UserState;

                            //控件Invoke
                            progessForm.Invoke(new EventHandler(delegate
                            {
                                switch (progressInformation.ProgressType)
                                {
                                    case DicomDirProgressType.Preparing:
                                        progessForm.counterLabel.Text = String.Format("Preparing Data ( {0} % )",
                                            percentage);
                                        break;
                                    case DicomDirProgressType.LoadingImages:
                                        if (progressInformation.SeriesCount == 1)
                                            progessForm.counterLabel.Text = String.Format(
                                                "Loading... Image ( {0} / {1} )", progressInformation.CurrentFrame + 1,
                                                progressInformation.FrameCount);
                                        else
                                            progessForm.counterLabel.Text =
                                                String.Format("Loading... Series ( {0} / {1} ) Image ( {2} / {3} )",
                                                    progressInformation.CurrentSeries + 1,
                                                    progressInformation.SeriesCount,
                                                    progressInformation.CurrentFrame + 1, progressInformation.FrameCount);
                                        break;
                                }
                                //设置进度条的相关值
                                progessForm.progressCounter.Value = percentage;
                                progessForm.progressCounter.Update();
                            }));
                        }
                    }
                });
            //给imagesLoader追加事件，关闭进度条窗口
            mainPanel.seriesBrowserDialog.imagesLoader.RunWorkerCompleted +=
                new System.ComponentModel.RunWorkerCompletedEventHandler((s, arg) =>
                {
                    progessForm.Close();
                    progessForm.Dispose();
                    progessForm = null;
                });
            mainPanel.OnOpenDir += MainPanel_OnOpenDir;
            if (args != null)
            {
                ShowOrderByOrderNumber(args.OrderNumber);
            }
        }

        /// <summary>
        /// win消息事件处理重写
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == DICOMViewer.Utility.WinMessageUtility.WM_COPYDATA)
                //根据Message.Msg区分消息类型，ImportFromDLL.WM_COPYDATA为发送方定义的消息类型
            {
                string[] formNameAry = new string[]
                {
                    "ServerSettingEditForm", "LocalSettingForm", "ServerSettingForm", "ProgressForm", "WaitForm",
                    "CounterDialog"
                };
                for (int i = 0; i < formNameAry.Length; i++)
                {
                    IntPtr ipt =
                        DICOMViewer.Utility.WinMessageUtility.FindWindow(null, formNameAry[i]);
                    if (ipt != IntPtr.Zero)
                    {
                        if (i > 2) return; //后几种弹出都代表目前正在处理特殊通讯等操作，需要等待！
                        (Form.FromHandle(ipt) as Form).DialogResult = DialogResult.Cancel;
                    }
                }
                DICOMViewer.Utility.CopyDataStruct copyData =
                    (DICOMViewer.Utility.CopyDataStruct) m.GetLParam(typeof (DICOMViewer.Utility.CopyDataStruct));
                string[] args = copyData.lpData.Split(' ');
                DICOMViewer.Utility.ApplicationArgsUtility.Excute(args, this);
                this.WindowState = FormWindowState.Maximized;
            }
            base.WndProc(ref m);
        }

        public void ShowOrderByOrderNumber(string orderNumber)
        {
            this.bindPanel.ReFreshOrder(orderNumber);
        }

        #region 窗口关闭相关

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (cfind != null)
            {
                cfind.Terminate();
                cfind.CloseForced(true);
            }
        }

        #endregion

        /// <summary>
        /// DicomDir读取完毕之后的事件，主要用于构成seriesListView的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mainPanel_DicomDirAdded(object sender, EventArgs e)
        {
            this.listViewSeries.Clear();
            //获取在ainPanel.seriesBrowserDialog中已处理完成的StudyBrowserDataSet
            StudyBrowserDataSet seriesDs = mainPanel.seriesBrowserDialog.seriesDataSet;
            this.listViewSeries.BeginUpdate();
            this.listViewSeries.View = View.LargeIcon;
            ImageList imageList = new ImageList();
            //设置ListViewSeries中图片的大小
            imageList.ImageSize = new System.Drawing.Size(110, 100);
            List<ListViewItem> viewItemList = new List<ListViewItem>();
            //根据mainPanel.seriesBrowserDialog中已处理完成的StudyBrowserDataSet的数据生成ListView的item
            for (int i = 0; i < seriesDs.SeriesTable.Rows.Count; i++)
            {
                StudyBrowserDataSet.SeriesTableRow row =
                    seriesDs.SeriesTable.Rows[i] as StudyBrowserDataSet.SeriesTableRow;
                imageList.Images.Add(row.Thumbnail);
                ListViewItem lvi = new ListViewItem();
                lvi.ImageIndex = i;
                lvi.Text = "序列号：" + row.SeriesNumber + " 图片数：" + row.FrameCount;
                lvi.Tag = row.SeriesInstanceUID;
                viewItemList.Add(lvi);
            }
            this.listViewSeries.LargeImageList = imageList;
            this.listViewSeries.Items.AddRange(viewItemList.ToArray());
            this.listViewSeries.EndUpdate();
            this.bindPanel.RefreshLocalGrid();
            this.tabControl_main.SelectedTabPageIndex = 2;
        }

        #region Cfind相关事件函数

        private void cfind_Status(object sender, StatusEventArgs e)
        {
            var message = "Unknown Error";
            var action = "";
            var done = false;

            if (e.Type == StatusType.Error)
            {
                action = "Error";
                message = "Error occurred.\r\n";
                message += "\tError code is:\t" + e.Error;
            }
            else
            {
                switch (e.Type)
                {
                    case StatusType.ConnectFailed:
                        action = "Connect";
                        message = "Operation failed.";
                        done = true;
                        break;
                    case StatusType.ConnectSucceeded:
                        action = "Connect";
                        message = "Operation succeeded.\r\n";
                        message += "\tPeer Address:\t" + e.PeerIP + "\r\n";
                        message += "\tPeer Port:\t\t" + e.PeerPort;
                        break;
                    case StatusType.SendAssociateRequest:
                        action = "Associate Request";
                        message = "Request sent.";
                        break;
                    case StatusType.ReceiveAssociateAccept:
                        action = "Associcated Accept";
                        message = "Received.\r\n";
                        message += "\tCalling AE:\t" + e.CallingAE + "\r\n";
                        message += "\tCalled AE:\t" + e.CalledAE;
                        break;
                    case StatusType.ReceiveAssociateRequest:
                        action = "Associcated Request";
                        message = "Received.\r\n";
                        message += "\tCalling AE:\t" + e.CallingAE + "\r\n";
                        message += "\tCalled AE:\t" + e.CalledAE;
                        break;
                    case StatusType.ReceiveAssociateReject:
                        action = "Associate Reject";
                        message = "Received Associate Reject!";
                        message += "\r\n\tSource: " + e.Source;
                        message += "\r\n\tResult: " + e.Result;
                        message += "\r\n\tReason: " + e.Reason;
                        done = true;
                        break;
                    case StatusType.AbstractSyntaxNotSupported:
                        action = "Error";
                        message = "Abstract Syntax NOT supported!";
                        done = true;
                        break;
                    case StatusType.SendCFindRequest:
                        action = "C-FIND";
                        message = "Sending request";
                        break;
                    case StatusType.ReceiveCFindResponse:
                        action = "C-FIND";
                        if (e.Error == DicomExceptionCode.Success)
                        {
                            message = "Operation completed successfully.";
                        }
                        else
                        {
                            if (e.Status == DicomCommandStatusType.Pending)
                            {
                                message = "Additional operations pending.";
                            }
                            else
                            {
                                message = "Error in response Status code is: " + e.Status;
                            }
                        }
                        break;
                    case StatusType.ConnectionClosed:
                        action = "Connect";
                        message = "Network Connection closed!";
                        done = true;
                        break;
                    case StatusType.ProcessTerminated:
                        action = "";
                        message = "Process has been terminated!";
                        done = true;
                        break;
                    case StatusType.SendReleaseRequest:
                        action = "Release Request";
                        message = "Request sent.";
                        break;
                    case StatusType.ReceiveReleaseResponse:
                        action = "Release Response";
                        message = "Response received.";
                        done = true;
                        break;
                    case StatusType.SendCMoveRequest:
                        action = "C-MOVE";
                        message = "Sending request";
                        break;
                    case StatusType.ReceiveCMoveResponse:
                        action = "C-MOVE";
                        message = "Received response\r\n";
                        message += "\tStatus: " + e.Status + "\r\n";
                        message += "\tNumber Completed: " + e.NumberCompleted + "\r\n";
                        message += "\tNumber Remaining: " + e.NumberRemaining;
                        break;
                    case StatusType.SendCStoreResponse:
                        action = "C-STORE";
                        message = "Sending response";
                        break;
                    case StatusType.ReceiveCStoreRequest:
                        action = "C-STORE";
                        message = "Received request";
                        break;
                    case StatusType.Timeout:
                        message = "Communication timeout. Process will be terminated.";
                        done = true;
                        break;
                }
            }
            Console.WriteLine(string.Format("cfind status action:{0}  message:{1}", action, message));
        }

        private void cfind_FindComplete(object sender, FindCompleteEventArgs e)
        {
            switch (e.Type)
            {
                case FindType.StudySeries:
                    //创建保存图片的文件夹
                    Directory.CreateDirectory(workPath);
                    int SeriesInstancenumber = 0;
                    foreach (DicomDataSet ds in e.Datasets)
                    {
                        var SeriesInstanceUID = Utils.GetStringValue(ds, DemoDicomTags.SeriesInstanceUID);
                        SeriesInstancenumber +=
                            int.Parse(Utils.GetStringValue(ds, DemoDicomTags.NumberOfSeriesRelatedInstances));
                        queue.Enqueue(SeriesInstanceUID);
                    }
                    if (th == null || (th != null && !th.IsAlive))
                    {
                        //启动新线程并异步发送获取Series请求！
                        th = new Thread(() =>
                        {
                            //将线程归到cfind的workthread结束之后运行
                            cfind.workThread.Join();
                            //考虑到一直只有一个线程访问queue，这里不加锁了
                            if (queue.Count <= 0) return;

                            SendMoveSeriesCmd();
                            waitForm = new WaitForm(this);
                            new Thread(() => { waitForm.ShowDialog(); }).Start();
                        });
                    }
                    th.Start();
                    break;
            }
        }

        private WaitForm waitForm;

        private void cfind_MoveComplete(object sender, MoveCompleteEventArgs e)
        {
            for (var i = 0; i < e.Datasets.Count; i++)
            {
                DicomDataSet ds = e.Datasets[i];
                string instanceUid = Utils.GetStringValue(ds, DemoDicomTags.SOPInstanceUID);
                //按照jpeg2000格式压缩图像
                //Utility.ImageConverter.ConvertJpeg2000(ds);
                //将DataSet保存为dcm文件
                ds.Save(workPath + "\\" + instanceUid + ".dcm",
                    DicomDataSetSaveFlags.None);
                ds.Dispose();
            }

            //获取完成！
            if (queue.Count <= 0)
            {
                if (!Utility.DicomDirMaker.IsDicomPathCorrect(workPath))
                {
                    this.Invoke(new EventHandler(delegate
                    {
                        waitForm.Invoke(new EventHandler(delegate
                        {
                            waitForm.DialogResult = DialogResult.OK;
                            waitForm.Close();
                            waitForm.Dispose();
                            waitForm = null;
                        }));
                        this.Enabled = true;
                        MessageBox.Show("所选文件路径中不包含Dicom文件！");
                    }));
                    return;
                }
                //调用函数构建DicomDir
                Utility.DicomDirMaker.CreateDicomDirectory(workPath);
                //通过Invoke控件Tabcontrol来驱动3DViewer读取数据
                this.Invoke(new EventHandler(delegate
                {
                    //直接调用mainPanel中seriesBrowserDialog窗口的相关方法，窗口已被隐藏
                    mainPanel.seriesBrowserDialog.AddDicomDirectory(workPath + "\\DICOMDIR");
                    waitForm.Invoke(new EventHandler(delegate
                    {
                        waitForm.DialogResult = DialogResult.OK;
                        waitForm.Close();
                        waitForm.Dispose();
                        waitForm = null;
                    }));
                    this.Enabled = true;
                    this.tabControl_main.SelectedTabPageIndex = 2;
                }));
                return;
            }
            //获取尚未完成！继续异步排队！
            if (th == null || (th != null && !th.IsAlive))
            {
                th = new Thread(() =>
                {
                    Console.Out.WriteLine("th start!");
                    cfind.workThread.Join();
                    if (queue.Count > 0)
                    {
                        Console.Out.WriteLine("send move!");
                        SendMoveSeriesCmd();
                    }
                });
            }
            th.Start();
        }

        private void SendMoveSeriesCmd()
        {
            if (queue.Count <= 0) return;
            seriesInstance = queue.Dequeue();
            cfind.MoveSeries(bindPanel.selectedServer, bindPanel.clientConfig.AETitle, patientId, studyInstance,
                seriesInstance, bindPanel.clientConfig.Port);
        }

        #endregion

        private void listViewSeries_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string[] seriesInstanceAry = new string[this.listViewSeries.SelectedItems.Count];

            for (int i = 0; i < seriesInstanceAry.Length; i++)
            {
                seriesInstanceAry[i] = listViewSeries.SelectedItems[i].Tag.ToString();
            }

            //清除原有数据，这样的话目前只支持一组数据显示
            mainPanel._menuDeleteAll_Click(null, null);
            //初始化进度条窗口
            progessForm = new ProgressForm(this);
            //启动后台构建图像线程。
            mainPanel.seriesBrowserDialog.OuterInitializeBackgroundWorker(seriesInstanceAry, studyInstance,
                workPath + "\\DICOMDIR");
            progessForm.ShowDialog();
        }

        /// <summary>
        /// 本地Grid双击，直接打开相关的Dicom文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BindPanel_LocalGridDoubleClicked(object sender, LocalGridDoubleClickedArg e)
        {
            this.listViewSeries.Clear();
            studyInstance = e.StudyIntanceUID;
            //创建存放dcm文件的文件夹
            workPath = Application.StartupPath + "\\dicomfile\\" + studyInstance;
            if (!Directory.Exists(workPath))
            {
                DialogResult result = MessageBox.Show("相关检查的文件夹不存在", "注意",
                    MessageBoxButtons.OK);
                return;
            }

            //通过Invoke控件Tabcontrol来驱动3DViewer读取数据
            this.tabControl_main.Invoke(new EventHandler(delegate
            {
                //直接调用mainPanel中seriesBrowserDialog窗口的相关方法，窗口已被隐藏
                //清除原有数据和状态
                mainPanel.seriesBrowserDialog.btnClear_Click(null, null);
                mainPanel._menuDeleteAll_Click(null, null);

                this.listViewSeries.Clear();
                //读取目录
                mainPanel.seriesBrowserDialog.AddDicomDirectory(e.DicomDirPath);
            }));
            return;
        }

        /// <summary>
        /// 绑定自定义控件的通讯Grid双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BindPanel_ServerGridDoubleClicked(object sender, ServerGridDoubleClickedArg e)
        {
            patientId = e.PatientID;
            studyInstance = e.StudyIntanceUID;
            if (!string.IsNullOrEmpty(studyInstance))
            {
                //创建存放dcm文件的文件夹
                workPath = Application.StartupPath + "\\dicomfile\\" + studyInstance;
                if (Directory.Exists(workPath))
                {
                    DialogResult result = MessageBox.Show("当前Study相关文件已存在，选Yes重新下载，选No直接读取文件。", "注意",
                        MessageBoxButtons.YesNo);
                    if (result == DialogResult.No)
                    {
                        //通过Invoke控件Tabcontrol来驱动3DViewer读取数据
                        this.tabControl_main.Invoke(new EventHandler(delegate
                        {
                            //直接调用mainPanel中seriesBrowserDialog窗口的相关方法，窗口已被隐藏
                            //清除原有数据和状态
                            mainPanel.seriesBrowserDialog.btnClear_Click(null, null);
                            mainPanel._menuDeleteAll_Click(null, null);

                            this.listViewSeries.Clear();
                            //读取目录
                            mainPanel.seriesBrowserDialog.AddDicomDirectory(workPath + "\\DICOMDIR");
                        }));
                        return;
                    }
                }

                CFindQuery query = new CFindQuery();
                query.StudyInstanceUid = studyInstance;
                query.PatientID = patientId;
                cfind.Find(bindPanel.selectedServer, FindType.StudySeries, query, bindPanel.clientConfig.AETitle);
            }
        }

        private void MainPanel_OnOpenDir(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.RootFolder = Environment.SpecialFolder.Desktop;
            if (fbd.ShowDialog() != DialogResult.OK) return;
            new Thread(() =>
            {
                workPath = fbd.SelectedPath;
                this.Invoke(new EventHandler(delegate
                {
                    //直接调用mainPanel中seriesBrowserDialog窗口的相关方法，窗口已被隐藏
                    //清除原有数据和状态
                    mainPanel.seriesBrowserDialog.btnClear_Click(null, null);
                    mainPanel._menuDeleteAll_Click(null, null);

                    this.listViewSeries.Clear();
                    if (!Utility.DicomDirMaker.IsDicomPathCorrect(workPath))
                    {
                        this.Invoke(new EventHandler(delegate
                        {
                            waitForm.Invoke(new EventHandler(delegate{
                                waitForm.DialogResult = DialogResult.OK;
                                waitForm.Close();
                                waitForm.Dispose();
                                waitForm = null;
                            }));
                            this.Enabled = true;
                            MessageBox.Show("所选文件路径中不包含Dicom文件！");
                        }));
                        return;
                    }
                    Utility.DicomDirMaker.CreateDicomDirectory(workPath);
                    DicomDataSet ds = new DicomDataSet();
                    ds.Load(workPath + "\\DICOMDIR", DicomDataSetLoadFlags.None);
                    // get first patient element.
                    DicomElement patientElement = ds.GetFirstKey(null, true);
                    DicomElement dicomElement;
                    dicomElement = ds.GetChildElement(patientElement, true);
                    dicomElement = ds.FindFirstElement(dicomElement, DicomTag.PatientName, true);
                    string PatientName = ds.GetConvertValue(dicomElement);
                    // Get the first Study
                    dicomElement = ds.GetChildKey(patientElement);
                    dicomElement = ds.GetChildElement(dicomElement, true);
                    dicomElement = ds.FindFirstElement(dicomElement,
                        DicomTag.StudyInstanceUID,
                        true);

                    if (dicomElement != null)
                        studyInstance = ds.GetConvertValue(dicomElement);
                    patientElement = ds.GetNextKey(patientElement, true);
                    while (patientElement != null)
                    {
                        dicomElement = ds.GetChildElement(patientElement, true);
                        dicomElement = ds.FindFirstElement(dicomElement, DicomTag.PatientName, true);
                        string tempPatientName = ds.GetConvertValue(dicomElement) ?? string.Empty;
                        dicomElement = ds.GetChildKey(patientElement);
                        dicomElement = ds.GetChildElement(dicomElement, true);
                        dicomElement = ds.FindFirstElement(dicomElement,
                            DicomTag.StudyInstanceUID,
                            true);
                        string tempStudyInstanceUID = ds.GetConvertValue(dicomElement) ?? string.Empty;
                        //有两个病人根节点
                        if (dicomElement != null)
                        {
                            bool flag = false;
                            string errorMsg = string.Empty;
                            if (tempPatientName != PatientName)
                            {
                                Console.WriteLine("两个不同Patient！");
                                errorMsg = "此文件夹中包含一个以上病人的检查数据，无法打开！请选择仅包含单个病人单次检查数据的文件夹打开！";
                                flag = true;
                            }
                            if (studyInstance != tempStudyInstanceUID)
                            {
                                Console.WriteLine("两个不同Study！");
                                errorMsg = "此文件夹中包含一个以上的检查数据，无法打开！请选择仅包含单个病人单次检查数据的文件夹打开！";
                                flag = true;
                            }
                            if (flag)
                            {
                                waitForm.DialogResult = DialogResult.OK;
                                waitForm = null;
                                MessageBox.Show(errorMsg, "错误");
                                return;
                            }
                        }
                    }
                    //读取目录
                    mainPanel.seriesBrowserDialog.AddDicomDirectory(workPath + "\\DICOMDIR");
                    waitForm.DialogResult = DialogResult.OK;
                    waitForm = null;
                }));
            }).Start();
            waitForm = new WaitForm(this);
            waitForm.labelText = "正在读取文件...";
            waitForm.ShowDialog();
        }

        #region 窗口右上角按钮相关

        private void panel_title_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void panel_Title_Min_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void panel_Title_Normal_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Maximized;
            }
            else
            {
                this.WindowState = FormWindowState.Normal;
            }
        }

        #endregion
    }
}